<template>
  <div>
    <Button type="primary" class="back-button" @click="$router.push({name:'basic-rules-list'})" icon="md-arrow-back">返回上一级</Button>
    <Card>
      <Row class="title">
        <span>计算规则名称：{{model.ruleName}}</span>
        <Button v-if="kindCode != 20" @click="save" type="primary">保存全部</Button>
      </Row>
      <Tabs :value="tabName">
        <TabPane v-if="kindCode == 20" label="贡献值" name="eventsKindsGrade">
          <Row class="m-t-sm title">
            <span>贡献值</span>
            <Button @click="editKindsDevote()" type="primary" class="m-l-sm" icon="md-add">新增贡献值</Button>
          </Row>
          <Row class="m-t-sm">
            <Table ref="tableKindsTeam" :columns="columnDevote" stripe border :data="model.eventsKindsDevote"></Table>
            <Modal v-model="kindsDevoteVisible" width='800' :closable='false' :mask-closable='false' title="名次编辑">
              <Card>
                <Row>
                  <Col span="17" offset="3">
                  <Form ref='kindsDevote' :model="kindsDevote" :rules="kindsDevoteRules" inline :label-width='120'>
                    <FormItem prop='rank' label="开始名次" style="width:100%;">
                      <InputNumber v-model="kindsDevote.rank" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                    <FormItem prop='endRank' label="结束名次" style="width:100%;">
                      <InputNumber v-model="kindsDevote.endRank" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                    <FormItem prop='ratingPoints' label="贡献值" style="width:100%;">
                      <InputNumber v-model="kindsDevote.ratingPoints" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                  </Form>
                  </Col>
                </Row>
              </Card>
              <div slot="footer">
                <Button @click="cancelDevote">取消</Button>
                <Button @click="saveKindsDevote" class="m-l-md" type="primary">确认</Button>
              </div>
            </Modal>
          </Row>

        </TabPane>
        <TabPane v-if="kindCode != 20" label="赛事等级" name="eventsKindsGrade">
          <!-- 赛事等级 -->
          <Row class="m-t-sm title">
            <span>赛事等级</span>
            <Button @click="editKindsGrade()" type="primary" icon="md-add">新增赛事等级</Button>
          </Row>
          <Row class="m-t-sm">
            <Table ref="grade" :loading="kindsGradeLoading" :columns="columnKindsGrade" stripe border :data="model.eventsKindsGrade"></Table>
            <Modal v-model="kindsGradeVisible" width='800' :closable='false' :mask-closable='false' title="等级编辑">
              <Card>
                <Row>
                  <Col span="17" offset="3">
                  <Form ref='kindsGrade' :model="kindsGrade" :rules="kindsGradeRules" inline :label-width='100'>
                    <FormItem prop='grandCode' label="等级code" style="width:100%;">
                      <InputNumber v-model="kindsGrade.grandCode" :value="kindsGrade.grandCode" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                    <FormItem prop='grandName' label="等级名称" style="width:100%;">
                      <Input v-model="kindsGrade.grandName" clearable placeholder="请输入" style="width:100%;"></Input>
                    </FormItem>
                    <FormItem prop='baseRatio' label="级别系数" style="width:100%;">
                      <InputNumber v-model="kindsGrade.baseRatio" :value="kindsGrade.baseRatio" :formatter="value => `${value||1}%`" :parser="value => value.replace('%', '')" :min="0" :max="1000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                    <FormItem prop='teamFlag' label="是否有阵容值" style="width:100%;">
                      <i-switch v-model="kindsGrade.teamFlag" :value="kindsGrade.teamFlag" size="large" :true-value='1' :false-value='0'>
                        <span slot="open">是</span>
                        <span slot="close">否</span>
                      </i-switch>
                    </FormItem>
                  </Form>
                  </Col>
                </Row>
              </Card>
              <div slot="footer">
                <Button @click="cancelKindsGrade">取消</Button>
                <Button @click="saveKindsGrade" class="m-l-md" type="primary">确认</Button>
              </div>
            </Modal>
          </Row>
        </TabPane>
        <TabPane v-if="kindCode != 20" label="名次积分对照" name="eventsKindsRank">
          <!-- 名次 -->
          <Row class="m-t-sm title">
            <span>名次积分对照</span>
            <Button @click="delKindsRank()" type="primary" class="m-l-sm" icon="md-trash">批量删除</Button>
            <Button @click="editKindsRank2()" type="primary" class="m-l-sm" icon="md-add">新增参赛积分</Button>
            <Button @click="editKindsRank()" type="primary" class="m-l-sm" icon="md-add">新增名次</Button>
            <upload-excel-button @upload="importKindsRank" class="m-l-sm" style="float:right;" text="模板导入"></upload-excel-button>
            <Button @click="exportKindsRank()" type="primary">下载模板</Button>
          </Row>
          <Row v-if="kindsRankShow" class="m-t-sm">

            <Table ref="tableKindsRank" :loading="kindsRankLoading" :columns="columnKindsRank" stripe border :data="model.eventsKindsRank"></Table>
            <Modal v-model="kindsRankVisible" width='800' :closable='false' :mask-closable='false' title="名次编辑">
              <Card>
                <Row>
                  <Col span="17" offset="3">
                  <Form ref='kindsRank' :model="kindsRank" :rules="kindsRankRules" inline :label-width='100'>
                    <FormItem v-if="kindsRank.rankStart!==-1" prop='rankStart' label="开始名次" style="width:100%;">
                      <InputNumber v-model="kindsRank.rankStart" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                    <FormItem v-if="kindsRank.rankEnd!==-1" prop='rankEnd' label="结束名次" style="width:100%;">
                      <InputNumber v-model="kindsRank.rankEnd" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                    <FormItem v-if="kindsRank.rankStart===-1" label="参赛积分" style="width:100%;">
                      安慰奖，有且只有一个
                    </FormItem>
                    <FormItem prop='baseRatio' label="名次系数" style="width:100%;">
                      <InputNumber v-model="kindsRank.baseRatio" :formatter="value => `${value||1}%`" :parser="value => value.replace('%', '')" :min="0" :max="100" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                  </Form>
                  </Col>
                </Row>
              </Card>
              <div slot="footer">
                <Button @click="cancelKindsRank">取消</Button>
                <Button @click="saveKindsRank" class="m-l-md" type="primary">确认</Button>
              </div>
            </Modal>
          </Row>
        </TabPane>
        <TabPane label="阵容值" v-if="hasKindsTeam && kindCode != 20" name="eventsKindsTeam">
          <!-- 阵容值 -->
          <Row v-if="hasKindsTeam" class="m-t-sm title">
            <span>阵容值</span>
            <Button @click="delKindsTeam()" type="primary" class="m-l-sm" icon="md-trash">批量删除</Button>
            <Button @click="editKindsTeam()" type="primary" class="m-l-sm" icon="md-add">新增阵容值</Button>
            <upload-excel-button @upload="importKindsTeam" class="m-l-sm" style="float:right;" text="模板导入"></upload-excel-button>
            <Button @click="exportKindsTeam()" type="primary">下载模板</Button>
          </Row>
          <Row v-if="hasKindsTeam" class="m-t-sm">
            <Table ref="tableKindsTeam" :loading="kindsTeamLoading" :columns="columnKindsTeam" stripe border :data="model.eventsKindsTeam"></Table>
            <Modal v-model="kindsTeamVisible" width='800' :closable='false' :mask-closable='false' title="名次编辑">
              <Card>
                <Row>
                  <Col span="17" offset="3">
                  <Form ref='kindsTeam' :model="kindsTeam" :rules="kindsTeamRules" inline :label-width='120'>
                    <FormItem prop='rankStart' label="CAGR排名起始" style="width:100%;">
                      <InputNumber v-model="kindsTeam.rankStart" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                    <FormItem prop='rankEnd' label="CAGR排名截止" style="width:100%;">
                      <InputNumber v-model="kindsTeam.rankEnd" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                    <FormItem prop='teamValue' label="阵容值" style="width:100%;">
                      <InputNumber v-model="kindsTeam.teamValue" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                  </Form>
                  </Col>
                </Row>
              </Card>
              <div slot="footer">
                <Button @click="cancelKindsTeam">取消</Button>
                <Button @click="saveKindsTeam" class="m-l-md" type="primary">确认</Button>
              </div>
            </Modal>
          </Row>
        </TabPane>
        <TabPane label="阵容加分" v-if="hasKindsTeam && kindCode != 20" name="teamScores">
          <!-- 阵容加分 -->
          <Row v-if="hasKindsTeam" class="m-t-sm title">
            <span>阵容加分</span>
            <Button @click="delTeamScore()" type="primary" class="m-l-sm" icon="md-trash">批量删除</Button>
            <Button @click="editTeamScore()" type="primary" class="m-l-sm" icon="md-add">新增阵容加分</Button>
            <upload-excel-button @upload="importTeamScore" class="m-l-sm" style="float:right;" text="模板导入"></upload-excel-button>
            <Button @click="exportTeamScore()" type="primary">下载模板</Button>
          </Row>
          <Row v-if="hasKindsTeam" class="m-t-sm">
            <Table ref="tableTeamScore" :loading="teamScoreLoading" :columns="columnTeamScore" stripe border :data="model.teamScores"></Table>
            <Modal v-model="teamScoreVisible" width='800' :closable='false' :mask-closable='false' title="名次编辑">
              <Card>
                <Row>
                  <Col span="17" offset="3">
                  <Form ref='teamScore' :model="teamScore" :rules="teamScoreRules" inline :label-width='120'>
                    <FormItem prop='grandCode' label="等级code" style="width:100%;">
                      <Select v-model="teamScore.grandCode" placeholder="请选择" clearable style="width: 100%;">
                        <Option v-for="(_item,index) in hasKindsTeams" :key="index" :value="_item.grandCode">{{_item.grandName}}</Option>
                      </Select>
                    </FormItem>
                    <FormItem prop='teamStart' label="开始阵容加分" style="width:100%;">
                      <InputNumber v-model="teamScore.teamStart" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                    <FormItem prop='teamEnd' label="结束阵容加分" style="width:100%;">
                      <InputNumber v-model="teamScore.teamEnd" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                    </FormItem>
                    <FormItem prop='scoreAdd' label="分值" style="width:100%;">
                      <InputNumber v-model="teamScore.scoreAdd" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                    </FormItem>
                  </Form>
                  </Col>
                </Row>
              </Card>
              <div slot="footer">
                <Button @click="cancelTeamScore">取消</Button>
                <Button @click="saveTeamScore" class="m-l-md" type="primary">确认</Button>
              </div>
            </Modal>
          </Row>
        </TabPane>

      </Tabs>

    </Card>
    <spin-temp v-if="loading"></spin-temp>
  </div>
</template>
<script>
import dict from "_c/dict/dict.vue";
import dictSpan from "_c/dict/dict-span.vue";
import uploadExcelButton from "_c/upload/upload-excel-button.vue";
import Api from "@/api/basic-rules";
import uuid from "uuid/v4";
import _ from "lodash";
const api = new Api();
export default {
  components: {
    dict,
    dictSpan,
    uploadExcelButton
  },
  data() {
    return {
      tabName: "eventsKindsGrade",
      kindCode: this.$route.params.id,
      loading: true,
      kindsGrade: {},
      kindsGradeLoading: false,
      kindsGradeVisible: false,
      ruleId: this.$route.params.id,
      hasKindsTeam: false,
      hasKindsTeams: [],
      kindsRank: {},
      kindsRankLoading: false,
      kindsRankShow: false,
      kindsRankVisible: false,
      kindsTeam: {},
      kindsTeamLoading: false,
      devoteLoading: false,
      kindsDevote: {},
      kindsTeamVisible: false,
      kindsDevoteVisible: false,
      teamScore: {},
      teamScoreLoading: false,
      teamScoreVisible: false,
      model: {
        eventsKindsGrade: [],
        eventsKindsRank: [],
        eventsKindsTeam: [],
        teamScores: [],
        eventsKindsDevote: []
      },
      // 赛事级别
      kindsGradeRules: {
        grandCode: [{ required: true, message: "请输入" }],
        grandName: [
          {
            required: true,
            message: "请输入"
          }
        ],
        baseRatio: [
          {
            required: true,
            message: "请输入"
          }
        ]
      },
      // 名次
      kindsRankRules: {
        rankStart: [{ required: true, message: "请输入" }],
        rankEnd: [
          {
            required: true,
            message: "请输入"
          }
        ],
        baseRatio: [
          {
            required: true,
            message: "请输入"
          }
        ]
      },
      // 阵容值
      kindsTeamRules: {
        rankStart: [{ required: true, message: "请输入" }],
        rankEnd: [
          {
            required: true,
            message: "请输入"
          }
        ],
        teamValue: [
          {
            required: true,
            message: "请输入"
          }
        ]
      },
       // 贡献值
      kindsDevoteRules: {
        rank: [{ required: true, message: "请输入" }],
        endRank: [
          {
            required: true,
            message: "请输入"
          }
        ],
        ratingPoints: [
          {
            required: true,
            message: "请输入"
          }
        ]
      },
      // 阵容加分
      teamScoreRules: {
        grandCode: [{ required: true, message: "请输入" }],
        teamStart: [{ required: true, message: "请输入" }],
        teamEnd: [
          {
            required: true,
            message: "请输入"
          }
        ],
        scoreAdd: [
          {
            required: true,
            message: "请输入"
          }
        ]
      },
      // 赛事级别
      columnKindsGrade: [
        {
          title: "等级code",
          key: "grandCode"
        },
        {
          title: "等级名称",
          key: "grandName"
        },
        {
          title: "等级系数",
          key: "baseRatio",
          render: (h, params) => {
            return h("span", params.row.baseRatio * 100 + "%");
          }
        },
        {
          title: "是否有阵容值",
          key: "teamFlag",
          render: (h, params) => {
            return h(dictSpan, {
              props: {
                code: "IS_FLAG",
                value: params.row.teamFlag
              }
            });
          }
        },
        {
          title: "操作",
          width: 150,
          render: (h, params) => {
            let self = this;
            return h("div", [
              h(
                "Button",
                {
                  style: {
                    marginRight: "5px"
                  },
                  props: { type: "primary", size: "small" },
                  on: {
                    click() {
                      self.editKindsGrade(params.index);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: { type: "error", size: "small" },
                  on: {
                    click() {
                      self.delKindsGrade(params.index);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      // 名次
      columnKindsRank: [
        {
          type: "selection",
          key: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "名次",
          key: "rankStart",
          render: (h, params) => {
            let title = this.$config.toStr(
              params.row.rankStart,
              params.row.rankEnd
            );
            if (params.row.rankStart === -1) {
              title = "参赛积分";
            }
            return h("span", title);
          }
        },
        {
          title: "名次系数",
          key: "baseRatio",
          render: (h, params) => {
            return h("span", this.$config.toPercent(params.row.baseRatio));
          }
        },
        {
          title: "操作",
          key: "action",
          width: 150,
          render: (h, params) => {
            let self = this;
            return h("div", [
              h(
                "Button",
                {
                  style: {
                    marginRight: "5px"
                  },
                  props: { type: "primary", size: "small" },
                  on: {
                    click() {
                      self.editKindsRank(params.index);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: { type: "error", size: "small" },
                  on: {
                    click() {
                      self.delKindsRank(params.index);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      // 阵容值
      columnKindsTeam: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "CAGR排名",
          key: "rankStart",
          render: (h, params) => {
            return h(
              "span",
              this.$config.toStr(params.row.rankStart, params.row.rankEnd)
            );
          }
        },
        {
          title: "阵容值",
          key: "teamValue",
          render: (h, params) => {
            return h("span", params.row.teamValue);
          }
        },
        {
          title: "操作",
          width: 150,
          render: (h, params) => {
            let self = this;
            return h("div", [
              h(
                "Button",
                {
                  style: {
                    marginRight: "5px"
                  },
                  props: { type: "primary", size: "small" },
                  on: {
                    click() {
                      self.editKindsTeam(params.index);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: { type: "error", size: "small" },
                  on: {
                    click() {
                      self.delKindsTeam(params.index);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      // 阵容加分
      columnTeamScore: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "赛事级别",
          key: "grandCode",
          render: (h, params) => {
            let obj = this.model.eventsKindsGrade.find(
              x => x.grandCode == params.row.grandCode
            ) || { grandName: "" };
            return h("span", obj.grandName);
          }
        },
        {
          title: "阵容值",
          key: "teamStart",
          render: (h, params) => {
            return h(
              "span",
              this.$config.toStr(params.row.teamStart, params.row.teamEnd)
            );
          }
        },
        {
          title: "阵容加分",
          key: "scoreAdd"
        },
        {
          title: "操作",
          width: 150,
          render: (h, params) => {
            let self = this;
            return h("div", [
              h(
                "Button",
                {
                  style: {
                    marginRight: "5px"
                  },
                  props: { type: "primary", size: "small" },
                  on: {
                    click() {
                      self.editTeamScore(params.index);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: { type: "error", size: "small" },
                  on: {
                    click() {
                      self.delTeamScore(params.index);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      // 贡献值
      columnDevote: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "名次",
          key: "rank",
          render: (h, params) => {
            return h(
              "span",
              this.$config.toStr(params.row.rank, params.row.endRank)
            );
          }
        },
        {
          title: "贡献值",
          key: "ratingPoints",
          render: (h, params) => {
            return h("span", params.row.ratingPoints);
          }
        },
        {
          title: "操作",
          width: 150,
          render: (h, params) => {
            let self = this;
            return h("div", [
              h(
                "Button",
                {
                  style: {
                    marginRight: "5px"
                  },
                  props: { type: "primary", size: "small" },
                  on: {
                    click() {
                      self.editKindsDevote(params.row);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Poptip",
                {
                  props: {
                    confirm: true,
                    title: "您确定要删除这条数据吗?",
                    transfer: true
                  },
                  on: {
                    "on-ok": () => {
                      self.delKindsDevote(params.row.id);
                    }
                  }
                },
                [
                  h(
                    "Button",
                    {
                      style: {
                        marginRight: "5px"
                      },
                      props: { type: "error", size: "small" }
                    },
                    "删除"
                  )
                ]
              ),
              // h(
              //   "Button",
              //   {
              //     props: { type: "error", size: "small" },
              //     on: {
              //       click() {
              //         self.delKindsDevote(params.row.id);
              //       }
              //     }
              //   },
              //   "删除"
              // )
            ]);
          }
        }
      ],
    };
  },
  mounted() {
    if(this.kindCode == 20) {
      this.getDevote()
    } else {
      this.getCycle();
    }
  },
  watch: {
    // tabName: {
    //   handler(n) {
    //     // if (n === "eventsKindsGrade") {
    //     //   console.log(this.$refs['grade']);
    //     // }
    //     // teamScoreLoading;
    //     // kindsTeamLoading;
    //     // kindsRankLoading;
    //   },
    //   immediate: true
    // },
    "model.eventsKindsGrade": {
      handler(n) {
        let hasKindsTeams = n.filter(x => x.teamFlag == 1);
        this.hasKindsTeams = hasKindsTeams;
        if (hasKindsTeams.length > 0) {
          this.hasKindsTeam = true;
        } else {
          this.hasKindsTeam = false;
        }
        this.kindsRankShow = false;
        let columnKindsRank = this.columnKindsRank.filter(x =>
          ["selection", "rankStart", "baseRatio", "action"].includes(x.key)
        );
        n.forEach(x => {
          columnKindsRank.splice(columnKindsRank.length - 2, 0, {
            title: x.grandName,
            key: x.grandCode,
            render: (h, params) => {
              return h(
                "span",
                this.$config.toNum(100 * params.row.baseRatio * x.baseRatio)
              );
            }
          });
        });
        this.columnKindsRank = columnKindsRank;
        this.kindsRankShow = true;
      },
      deep: true
    }
  },
  methods: {
    getDevote() {
      let self = this;
      self.loading = true;
      api
        .getDevote()
        .then(data => {
          self.model.eventsKindsDevote = data;
           self.model.eventsKindsDevote.sort((x,y)=> {return x.rank-y.rank})
          self.loading = false;
        })
        .catch(error => {
          self.loading = false;
        });
    },
    getVal(expression) {
      let self = this;
      eval(expression);
    },
    getCycle() {
      let self = this;
      self.loading = true;
      api
        .queryById(self.ruleId)
        .then(data => {
          self.model = data;
          if (self.model) {
            if (self.model.eventsKindsRank) {
              self.model.eventsKindsRank.forEach(x => {
                x.uuid = uuid();
              });
              self.model.eventsKindsRank.sort((x,y)=> {return x.grandCode-y.grandCode})
            }
            if (self.model.eventsKindsRank) {
              self.model.eventsKindsRank.sort((x,y)=> {
                if(x.rankStart===-1){
                  return true
                }
                return x.rankStart-y.rankStart
              })
            }
            if (self.model.eventsKindsTeam) {
              self.model.eventsKindsTeam.forEach(x => {
                x.uuid = uuid();
              });
              self.model.eventsKindsTeam.sort((x,y)=> {return x.rankStart-y.rankStart})
            }
            if (self.model.teamScores) {
              self.model.teamScores.forEach(x => {
                x.uuid = uuid();
              });
              self.model.teamScores.sort((x,y)=> {return x.teamStart-y.teamStart})
            }
          }
          self.loading = false;
        })
        .catch(error => {
          self.loading = false;
        });
    },
    // 保存规则
    save() {
      let self = this;
      self.loading = true;
      let params = { ...self.model };
      params.eventsKindsRank.forEach(x => {
        delete x.uuid;
      });
      params.eventsKindsTeam.forEach(x => {
        delete x.uuid;
      });
      params.teamScores.forEach(x => {
        delete x.uuid;
      });
      api
        .edit(self.model)
        .then(data => {
          self.loading = false;
          self.$router.push("/basic-rules-management/index");
        })
        .catch(error => {
          self.loading = false;
        });
    },
    editKindsGrade(index) {
      this.kindsGradeVisible = true;
      if (index == null) {
        this.kindsGrade = {
          grandCode: null,
          grandName: "",
          teamFlag: 0,
          baseRatio: 1
        };
      } else {
        let row = this.model.eventsKindsGrade[index];
        this.kindsGrade = {
          ...row,
          grandCode: Number(row.grandCode),
          baseRatio: row.baseRatio * 100,
          teamFlag: row.teamFlag == "1" ? 1 : 0,
          index
        };
      }
    },
    // 删除赛事级别
    delKindsGrade(index) {
      this.model.eventsKindsGrade.splice(index, 1);
    },
    // 保存赛事级别
    saveKindsGrade() {
      let self = this;
      self.$refs["kindsGrade"].validate(valid => {
        if (valid) {
          self.kindsGradeLoading = true;
          let model = {
            ...self.kindsGrade,
            baseRatio: self.kindsGrade.baseRatio / 100.0,
            teamFlag: self.kindsGrade.teamFlag == "1" ? 1 : 0
          };

          let index = self.kindsGrade.index;
          if (index == null) {
            self.model.eventsKindsGrade.push(model);
          } else {
            self.model.eventsKindsGrade[index] = _.omit(model, ["index"]);
            self.model.eventsKindsGrade = [...self.model.eventsKindsGrade];
          }
          self.kindsGradeLoading = false;
          self.cancelKindsGrade();
        }
      });
    },
    cancelKindsGrade() {
      this.kindsGradeVisible = false;
      this.$refs["kindsGrade"].resetFields();
      this.kindsGrade.teamFlag = 0;
    },
    editKindsRank(index) {
      this.kindsRankVisible = true;
      if (index == null) {
        this.kindsRank = {
          rankStart: null,
          rankEnd: null,
          baseRatio: 1,
          uuid: uuid()
        };
      } else {
        let row = this.model.eventsKindsRank[index];
        this.kindsRank = {
          ...row,
          baseRatio: row.baseRatio * 100,
          index
        };
      }
    },
    editKindsRank2(index) {
      this.kindsRankVisible = true;
      if (index == null) {
        index = this.model.eventsKindsRank.findIndex(x => x.rankStart === -1);
        if (index !== -1) {
          this.$Message.info(
            "参赛积分有且只有一个，已添加参赛积分，默认编辑这条参赛积分"
          );
        } else {
          index = null;
        }
      }
      if (index == null) {
        this.kindsRank = {
          rankStart: -1,
          rankEnd: -1,
          baseRatio: 4,
          uuid: uuid()
        };
      } else {
        let row = this.model.eventsKindsRank[index];
        this.kindsRank = {
          ...row,
          baseRatio: row.baseRatio * 100,
          index
        };
      }
    },
    // 删除名次
    delKindsRank(index) {
      let self = this;
      if (typeof index === "number") {
        self.model.eventsKindsRank.splice(index, 1);
      } else {
        let selection = _.map(self.$refs.tableKindsRank.getSelection(), "uuid");
        if (selection.length === 0) {
          self.$Message.warning("请选择要删除的名次");
          return;
        }

        self.model.eventsKindsRank = _.reject(self.model.eventsKindsRank, x =>
          selection.includes(x.uuid)
        );
      }
    },
    // 保存名次
    saveKindsRank() {
      let self = this;
      self.$refs["kindsRank"].validate(valid => {
        if (valid) {
          self.kindsRankLoading = true;
          let model = {
            ...self.kindsRank,
            baseRatio: self.kindsRank.baseRatio / 100.0
          };
          let index = self.kindsRank.index;
          if (index == null) {
            self.model.eventsKindsRank.push(model);
          } else {
            self.model.eventsKindsRank[index] = _.omit(model, ["index"]);
            self.model.eventsKindsRank = [...self.model.eventsKindsRank];
          }
          self.kindsRankLoading = false;
          self.cancelKindsRank();
        }
      });
    },
    cancelKindsRank() {
      this.kindsRankVisible = false;
      this.$refs["kindsRank"].resetFields();
    },
    exportKindsRank() {
      let link = document.createElement("a");
      link.href = this.$config.rankExcelTempUrl;
      link.download = "名次导入模板.xlsx";
      link.click();
    },
    importKindsRank(ftpFile) {
      let self = this;
      let { ruleId, model } = self;
      let params = {
        ruleId,
        ftpFile
      };
      api.importRank(params).then(data => {
        if (data != null) {
          data.forEach(x => {
            x.uuid = uuid();
          });
          model.eventsKindsRank = _.concat(model.eventsKindsRank, data);
        }
      });
    },
    editKindsTeam(index) {
      this.kindsTeamVisible = true;
      if (index == null) {
        this.kindsTeam = {
          rankStart: null,
          rankEnd: null,
          teamValue: null,
          uuid: uuid()
        };
      } else {
        this.kindsTeam = {
          ...this.model.eventsKindsTeam[index],
          index
        };
      }
    },
    // 贡献值弹窗
    editKindsDevote(record) {
      this.kindsDevoteVisible = true;
      if (record == null) {
        this.kindsDevote = {
          rank: null,
          endRank: null,
          ratingPoints: null,
        };
      } else {
        this.kindsDevote = {
          rank: record.rank,
          endRank: record.endRank,
          ratingPoints: record.ratingPoints,
          id: record.id
        };
      }
    },
    // 删除阵容值
    delKindsTeam(index) {
      let self = this;
      if (typeof index === "number") {
        self.model.eventsKindsTeam.splice(index, 1);
      } else {
        let selection = _.map(self.$refs.tableKindsTeam.getSelection(), "uuid");
        if (selection.length === 0) {
          self.$Message.warning("请选择要删除的阵容值");
          return;
        }

        self.model.eventsKindsTeam = _.reject(self.model.eventsKindsTeam, x =>
          selection.includes(x.uuid)
        );
      }
    },
    // 保存阵容值
    saveKindsTeam() {
      let self = this;
      self.$refs["kindsTeam"].validate(valid => {
        if (valid) {
          self.kindsTeamLoading = true;
          let model = {
            ...self.kindsTeam
          };
          let index = self.kindsTeam.index;
          if (index == null) {
            self.model.eventsKindsTeam.push(model);
          } else {
            self.model.eventsKindsTeam[index] = _.omit(model, ["index"]);
            self.model.eventsKindsTeam = [...self.model.eventsKindsTeam];
          }
          self.kindsTeamLoading = false;
          self.cancelKindsTeam();
        }
      });
    },
     // 删除贡献值
    delKindsDevote(id) {
      let self = this
      self.loading = true;
       api
        .delDevote(id)
        .then(data => {
          self.loading = false;
          self.getDevote()
        })
        .catch(error => {
          self.loading = false;
        });
    },
     // 保存贡献值
    saveKindsDevote() {
      let self = this;
      self.$refs["kindsDevote"].validate(valid => {
        if (valid) {
          self.devoteLoading = true;
          let model = {
            ...self.kindsDevote
          };
          let ranking = {
            rank: self.kindsDevote.rank,
            endRank: self.kindsDevote.endRank,
          }
          if(self.kindsDevote.id) {
            ranking.id = self.kindsDevote.id
          }
          api.repeatDevote(ranking)
            .then(data => {
              if(data) {
                self.loading = true;
                api.optDevote(model)
                  .then(data => {
                    self.loading = false;
                    self.getDevote()
                    })
                  .catch(error => {
                    self.loading = false;
                });
                self.devoteLoading = false;
                self.cancelDevote();
              } else {
                this.$Message.warning('此名次已存在,请重新输入')
              }
            })
        }
      });
    },
    cancelKindsTeam() {
      this.kindsTeamVisible = false;
      this.$refs["kindsTeam"].resetFields();
    },
    cancelDevote() {
      this.kindsDevoteVisible = false;
      this.$refs["kindsDevote"].resetFields();
    },
    exportKindsTeam() {
      let link = document.createElement("a");
      link.href = this.$config.teamExcelTempUrl;
      link.download = "阵容值导入模板.xlsx";
      link.click();
    },
    importKindsTeam(ftpFile) {
      let self = this;
      let { ruleId, model } = self;
      let params = {
        ruleId,
        ftpFile
      };
      api.importTeam(params).then(data => {
        if (data != null) {
          data.forEach(x => {
            x.uuid = uuid();
          });
          model.eventsKindsTeam = _.concat(model.eventsKindsTeam, data);
        }
      });
    },
    editTeamScore(index) {
      this.teamScoreVisible = true;
      if (index == null) {
        this.teamScore = {
          grandCode: null,
          teamStart: null,
          teamEnd: null,
          scoreAdd: null,
          uuid: uuid()
        };
      } else {
        this.teamScore = {
          ...this.model.teamScores[index],
          index
        };
      }
    },
    // 删除阵容加分
    delTeamScore(index) {
      let self = this;
      if (typeof index === "number") {
        self.model.teamScores.splice(index, 1);
      } else {
        let selection = _.map(self.$refs.tableTeamScore.getSelection(), "uuid");
        if (selection.length === 0) {
          self.$Message.warning("请选择要删除的阵容加分");
          return;
        }

        self.model.teamScores = _.reject(self.model.teamScores, x =>
          selection.includes(x.uuid)
        );
      }
    },
    // 保存阵容加分
    saveTeamScore() {
      let self = this;
      self.$refs["teamScore"].validate(valid => {
        if (valid) {
          self.teamScoreLoading = true;
          let model = {
            ...self.teamScore
          };
          let index = self.teamScore.index;
          if (index == null) {
            self.model.teamScores.push(model);
          } else {
            self.model.teamScores[index] = _.omit(model, ["index"]);
            self.model.teamScores = [...self.model.teamScores];
          }
          self.teamScoreLoading = false;
          self.cancelTeamScore();
        }
      });
    },
    cancelTeamScore() {
      this.teamScoreVisible = false;
      this.$refs["teamScore"].resetFields();
    },
    exportTeamScore() {
      let link = document.createElement("a");
      link.href = this.$config.teamScoreExcelTempUrl;
      link.download = "阵容加分导入模板.xlsx";
      link.click();
    },
    importTeamScore(ftpFile) {
      let self = this;
      let { ruleId, model } = self;
      let params = {
        ruleId,
        ftpFile
      };
      api.importTeamScore(params).then(data => {
        if (data != null) {
          data.forEach(x => {
            x.uuid = uuid();
          });
          model.teamScores = _.concat(model.teamScores, data);
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.title {
  span {
    font-weight: bold;
    font-size: 16px;
  }
  button {
    float: right;
  }
}
</style>
